package com.example.h5_share_demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.h5_share_demo.utils.AESUtils;
import com.example.h5_share_demo.utils.R;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @ClassName SpringFestivalController
 * @Description 春节活动
 * @Author zhangsw
 * @Date 2021/1/17 14:22
 * @Version 1.0
 */
@Controller
public class SpringFestivalController {

    /**
     * 加能量回调
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("addBullish")
    public Object TaskCallback(HttpServletRequest req) {
        JSONObject param = getJSONParam(req);
        //参数验证
        if (param == null) {
            return R.error(1, "入参不能为空");
        }
        if (StringUtils.isEmpty(param.getJSONObject("in").getString("params"))) {
            return R.error(2, "手机号不能为空");
        }
        if (StringUtils.isEmpty(param.getJSONObject("sec").getString("mac"))) {
            return R.error(3, "非法校验");
        }
        String macs = param.getJSONObject("in").getString("params");
        String decrypt = AESUtils.Decrypt(param.getJSONObject("sec").getString("mac"));
        if (!macs.equals(decrypt) || !macs.contains("&")) {
            return R.error(4, "字段校验不通过");
        }
        String[] split = macs.split("&");
        String phoneNum = split[0];
        String taskType = split[1];
        System.err.println(phoneNum);
        System.err.println(taskType);
        //
        //自己代码调用，去订购页面前先请求后台记录redis一下
        //当调用订购接口时，在接口调用成功内判断 当redis中有这个类型，才给他加能量否则不加
        Object o = TaskSuccessCallback("");
        return R.ok("ok");
    }

    /**
     * 任务成功回调
     * @return
     */
    public Object TaskSuccessCallback(String taskType) {

        return null;
    }

    public JSONObject getJSONParam(HttpServletRequest request) {
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
            // 直接将json信息打印出来
//            System.out.println(jsonParam.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }
}
